<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>组件-自定义事件</title>
  </head>
  <body>
    <!-- 子组件模板 -->
    <template id="child-template">
      <input v-model="msg" type="text" name="name" value="">
      <button @click="notify" type="button" name="button">Dispatch Event</button>
    </template>
    <!-- 父组件模板 -->
    <div id="app" class="">
      <p>Messages: {{messages | json}}</p>
      <child></child>
    </div>

    <script src="js/jquery-1.8.3.min.js" charset="utf-8"></script>
    <script src="js/vue.js" charset="utf-8"></script>
    <script type="text/javascript">
      //注册子组件
      Vue.component('child',{
        template:'#child-template',
        data: function(){
          return {msg:'hello'}
        },
        methods:{
          notify: function (){
            if(this.msg.trim()){
              this.$dispatch('child-msg',this.msg)
              this.msg=''
            }
          }
        }
      })

      //初始化父组件
      //将收到的消息推入一个数组
      var parent = new Vue({
        el:'#app',
        data:{
          messages:[]
        },
        //在创建实例时 'events' 选项简单的调用 '$on'
        events:{
          'child-msg':function(msg) {
            // 事件回调 'this' 自动绑定到注册它的实例上
            this.messages.push(msg)
          }
        }
      })
    </script>
  </body>
</html>
